package com.hengmei.smallscreen.ui

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.media.MediaScannerConnection
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.hengmei.smallscreen.R
import com.hengmei.smallscreen.ReadExcel.ReadExcel
import com.hengmei.smallscreen.adapter.HistoryAdapter
import com.hengmei.smallscreen.base.BaseActivity
import com.hengmei.smallscreen.databinding.ActivityHistoryBinding
import com.hengmei.smallscreen.db.datebase.AppDatabase
import com.hengmei.smallscreen.db.entity.HistoricalRecord
import com.hengmei.smallscreen.entity.UpDataEntity
import com.hengmei.smallscreen.mmkv.DataRepository
import com.hengmei.smallscreen.utils.AntiShake
import com.hengmei.smallscreen.utils.getCode
import com.hengmei.smallscreen.utils.log
import com.hengmei.smallscreen.utils.toast
import com.kongzue.baseokhttp.HttpRequest
import com.kongzue.baseokhttp.listener.ResponseListener
import com.kongzue.baseokhttp.util.Parameter
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.interfaces.OnBindView
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date


class HistoryActivity : BaseActivity<ActivityHistoryBinding>(ActivityHistoryBinding::inflate) {
    companion object {
        fun start(mainActivity: Activity) {
            mainActivity.startActivity(Intent(mainActivity, HistoryActivity::class.java))
        }
    }

    private var file: File? = null
    private var fileName: String? = null
    private var recordList:ArrayList<ArrayList<String>> ?= null
    private var title: Array<String>? = null
    private var adapter: HistoryAdapter? = null
    private var list: List<HistoricalRecord>? = null
    private val requestLocationPermission =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isPermissionGranted ->
            if (isPermissionGranted) {

            } else {
                toast("get Permission ERROR")
            }
        }
    override fun initView() {
        list = ArrayList()
        binding.historyRv.layoutManager = LinearLayoutManager(this)
        adapter = HistoryAdapter(
            R.layout.item_history,
            list
        )
        adapter?.addChildClickViewIds(R.id.ll_top)
        adapter?.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.ll_top -> {
                    if(list?.get(position)?.space1 == "1"){
                        list?.get(position)?.space1 = "0"
                        adapter.notifyDataSetChanged()
                    }else{
                        list?.get(position)?.space1 = "1"
                        adapter.notifyDataSetChanged()
                    }
                }
            }
        }
        adapter?.addChildLongClickViewIds(R.id.ll_top)
        adapter?.setOnItemChildLongClickListener { adapter, view, position ->
            when (view.id) {
                R.id.ll_top -> {
//                    弹窗显示具体数据
                    showDetailsDialog(list?.get(position))
                }
            }
            true
        }
        binding.historyRv.adapter = adapter
        initDB()
        title = arrayOf<String>(
            "ID",
            getString(R.string.project_name),
            getString(R.string.sampleName),
            getString(R.string.sampleCode),
            getString(R.string.waterContent),
            getString(R.string.unit),
            getString(R.string.inspector),
            getString(R.string.testingUnit),
            getString(R.string.UnitInspected),
            getString(R.string.Tel),
            getString(R.string.sampleTime)
        )
    }

    private fun showDetailsDialog(item: HistoricalRecord?) {


        CustomDialog.show(object :
            OnBindView<CustomDialog>(R.layout.dialog_details) {
            override fun onBind(dialog: CustomDialog, v: View) {
                val btn_ok: TextView = v.findViewById(R.id.confirm_button)
                val tvInspector = v.findViewById<TextView>(R.id.tv_inspector)
                val tvUnit = v.findViewById<TextView>(R.id.tv_unit)
                val tvBeUnit = v.findViewById<TextView>(R.id.et_be_unit)
                val tvTel = v.findViewById<TextView>(R.id.et_tel)
                val tvTime = v.findViewById<TextView>(R.id.tv_time)
//
//
//                tvInspector.setPaintFlags(tvInspector.getPaintFlags() or Paint.UNDERLINE_TEXT_FLAG)
//                tvUnit.setPaintFlags(tvUnit.getPaintFlags() or Paint.UNDERLINE_TEXT_FLAG)
//                tvBeUnit.setPaintFlags(tvBeUnit.getPaintFlags() or Paint.UNDERLINE_TEXT_FLAG)
//                tvTel.setPaintFlags(tvTel.getPaintFlags() or Paint.UNDERLINE_TEXT_FLAG)
//                tvTime.setPaintFlags(tvTime.getPaintFlags() or Paint.UNDERLINE_TEXT_FLAG)

                tvInspector.text = item?.testPerson
                tvUnit.text = item?.testUnit
                tvBeUnit.text = item?.beTestUnit
                tvTel.text = item?.tel
                tvTime.text = item?.testDate

                btn_ok.setOnClickListener(View.OnClickListener { v ->
                    if (AntiShake.check(v)) {
                        return@OnClickListener
                    }
                    dialog.dismiss()
                })

            }
        }).maskColor = Color.parseColor("#4D000000")

    }

    /*
    * 发起上传
    * */
    private fun goUp(dataList:List<HistoricalRecord>?):UpDataEntity{



        val address = DataRepository.upAddress
        val name = DataRepository.upUser
        val pwd = DataRepository.upPwd

        var list = ArrayList<UpDataEntity.DetailsDTO>()

        for(item in dataList!!){
            if(item!!.space1 == "1"){

                val inspector = item?.testPerson
                val unit = item?.testUnit
                val beUnit = item?.beTestUnit
                val tel = item?.tel
                val time = item?.testDate
                val content = item?.waterContent
                val temp = item?.temp
                val sampleName = item?.sampleName
                val sampleNum = item?.sampleNumber

                var details = UpDataEntity.DetailsDTO()
                details.jiancedidian = ""
                details.jiancejieguo = content
                details.jianceren = inspector
                details.jianceriqi = time
                details.jiancexiangmu = sampleName
                details.jiancezhi = content
                details.lianxidianhua = tel
                details.shanghumingcheng = beUnit
                details.yangpinbianhao = sampleNum
                details.yangpinmingcheng = sampleName
                list.add(details)
            }
        }

        var upDataEntity = UpDataEntity()
        upDataEntity.yqbh = getCode()
        upDataEntity.username = name
        upDataEntity.password = pwd
        upDataEntity.dwmc = DataRepository.unitInspected

        upDataEntity.details = list
        return upDataEntity
    }

    override fun initViewEvents() {
        setOnClickListener(
            binding.buttonBack,
            binding.buttonUp,
            binding.buttonExport,
            binding.buttonDel
        )
    }

    private fun initDB() {
//        初始化数据库数据
        launch {

            AppDatabase.getDataBase()?.historyDao()?.getAll()?.apply {
                list = this
                log("list = $list")
                adapter?.setList(list)
            }
        }
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        if (AntiShake.check(v)) {
            return
        }
        when (v) {
            binding.buttonBack -> {

                finish()
            }

            binding.buttonUp -> {


                var upStr  = goUp(list!!)
                HttpRequest.POST(me,
                    DataRepository.upAddress,
                    Parameter().add("modelJson", Gson().toJson(upStr)),
                    object : ResponseListener{
                        override fun onResponse(response: String?, error: Exception?) {

                            if (error == null) {
//                        resultHttp.setText(response);
                                Log.d("daank", response!!)
                                if (response == "-2" || response == "\"-2\"") {
                                    Toast.makeText(
                                        me,
                                        getString(R.string.wrongPassword),
                                        Toast.LENGTH_SHORT
                                    ).show()
                                    return
                                }
                                if (response == "-3" || response == "\"-3\"") {
                                    Toast.makeText(
                                        me,
                                        getString(R.string.failToUpload),
                                        Toast.LENGTH_SHORT
                                    ).show()
                                    return
                                }
                                if (response == "success" || response == "\"success\"") {
                                    Toast.makeText(
                                        me,
                                        getString(R.string.upHint),
                                        Toast.LENGTH_SHORT
                                    ).show()

                                    return
                                }
                                if (response == "fail" || response == "\"fail\"") {
                                    Toast.makeText(
                                        me,
                                        getString(R.string.failToUpload),
                                        Toast.LENGTH_SHORT
                                    ).show()
                                    return
                                }
                            } else {

                                Log.d("daank", error.toString())
                                Toast.makeText(
                                    me,
                                    getString(R.string.failToUpload),
                                    Toast.LENGTH_SHORT
                                ).show()

                            }
                        }
                    })

            }

            binding.buttonExport -> {

                launch {

                    val simpleDateFormat = SimpleDateFormat("yyyyMMddHHmmss") // HH:mm:ss

                    val date = Date(System.currentTimeMillis())
                    val a = simpleDateFormat.format(date)
                    val externalStoragePublicDirectory =
                        Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_DCIM
                        )
//判断是否有文件夹，没有则创建
if (!externalStoragePublicDirectory.exists()) {
                        externalStoragePublicDirectory.mkdirs()
                    }
//                    requestLocationPermission.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                    requestLocationPermission.launch(Manifest.permission.READ_EXTERNAL_STORAGE)

                    fileName =
                        externalStoragePublicDirectory.toString() + "/" + resources.getString(R.string.history_export) + a + ".xls" //得到导出目录
                    ReadExcel.initExcel(fileName, title)

                    ReadExcel.writeObjListToExcel(getRecordData(), fileName, me)


                    //扫描图片
                    MediaScannerConnection.scanFile(
                        me,
                        arrayOf<String>(fileName!!),
                        null
                    ) { s, uri -> log( "更新文件库成功") }

                }

            }

            binding.buttonDel -> {
//                确认弹窗
                MessageDialog.show(getString(R.string.hint), getString(R.string.delHint),
                    getString(R.string.affirm), getString(R.string.cancel))
                    .setOkButton { baseDialog, v ->
                        launch {
                            for (item in list!!) {
                                if (item.space1 == "1") {
                                    AppDatabase.getDataBase()?.historyDao()?.deleteHistory(item)
                                }
                            }
                            initDB()
                        }
                        false
                    }
            }
        }
    }


    /**
     * 将数据集合 转化成ArrayList<ArrayList></ArrayList><String>>
     *
     * @return
    </String> */
    private fun getRecordData():ArrayList<ArrayList<String>> {

        recordList = ArrayList()

        try {
            var haveSelect = false
            for (i in 0 until list?.size!!) {
                if (list?.get(i)?.space1!! == "1") {
                    haveSelect = true
                }
            }
            if (list?.size!! > 0 && haveSelect) {
                for (i in 0 until list?.size!!) {
                    if (list?.get(i)?.space1!! == "1") {
                        val beanList = ArrayList<String>()
                        beanList.add(list?.get(i)?.id.toString() )
                        beanList.add(list?.get(i)?.projectName!! )
                        beanList.add(list?.get(i)?.sampleName!! )
                        beanList.add(list?.get(i)?.sampleNumber!!)
                        beanList.add(list?.get(i)?.waterContent!!)
                        beanList.add("%")
                        list?.get(i)?.testPerson?.let { beanList.add(it) }
                        list?.get(i)?.testUnit?.let { beanList.add(it) }
                        list?.get(i)?.beTestUnit?.let { beanList.add(it) }
                        list?.get(i)?.tel?.let { beanList.add(it) }
                        list?.get(i)?.testDate?.let { beanList.add(it) }
                        recordList?.add(beanList)
                    }
                }
            } else {
                Toast.makeText(me, getString(R.string.无数据导出), Toast.LENGTH_SHORT)
                    .show()
            }
        } catch (e: java.lang.Exception) {
            Toast.makeText(me, getString(R.string.无数据导出), Toast.LENGTH_SHORT).show()
        }
        return recordList!!
    }
}